<template>
  <view class="user-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left">
        <view class="back-icon" @tap="goBack">
          <text class="back-text">←</text>
        </view>
      </view>
      <view class="nav-center">
        <text class="nav-title">我的</text>
      </view>
      <view class="nav-right">
        <view class="settings-icon" @tap="goToSettings">
          <text class="settings-text">⚙️</text>
        </view>
      </view>
    </view>

    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-bg">
        <image class="bg-image" src="https://ai-public.mastergo.com/ai/img_res/165c6f77412b962d593c294f033463f9.jpg" mode="aspectFill" />
        <view class="bg-overlay"></view>
      </view>
      
      <view class="user-info">
        <image :src="userInfo.avatar" class="user-avatar" mode="aspectFill" @tap="handleAvatarClick" />
        <view class="user-details">
          <view class="name-edit-container">
            <text class="user-name">{{ userInfo.nickname }}</text>
            <text class="edit-icon" @tap="showEditDialog" v-if="isLogin">✏️</text>
          </view>
          <text class="user-desc">{{ loginTypeText }}</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-title">我的音乐</view>
      <view class="menu-grid">
        <view class="menu-item" @tap="goToFavorites">
          <text class="menu-icon">❤️</text>
          <text class="menu-text">我的收藏</text>
        </view>
        <view class="menu-item" @tap="goToHistory">
          <text class="menu-icon">📊</text>
          <text class="menu-text">播放历史</text>
        </view>
        <view class="menu-item" @tap="goToDownload">
          <text class="menu-icon">⬇️</text>
          <text class="menu-text">下载管理</text>
        </view>
        <view class="menu-item" @tap="goToSettings">
          <text class="menu-icon">⚙️</text>
          <text class="menu-text">设置</text>
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-number">{{ playCount }}</text>
          <text class="stat-label">播放次数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ favoriteCount }}</text>
          <text class="stat-label">收藏歌曲</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ listenTime }}</text>
          <text class="stat-label">听歌时长</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section">
      <button class="action-btn logout-btn" @tap="handleLogout" v-if="isLogin">
        <text class="btn-text">退出登录</text>
      </button>
      <button class="action-btn login-btn" @tap="goToLogin" v-else>
        <text class="btn-text">立即登录</text>
      </button>
    </view>
  </view>
</template>

<script>
import userManager from '@/utils/user.js'
import mockFavoritesManager from '@/utils/mockFavorites.js'

export default {
  data() {
    return {
      userInfo: {
        nickname: '游客',
        avatar: '/static/logo.png',
        loginType: 'guest'
      },
      isLogin: false,
      playCount: 0,
      favoriteCount: 0,
      listenTime: '0小时',
      favoriteList: [], // 收藏列表
      editForm: {
        nickname: '',
        avatar: ''
      }
    }
  },
  
  computed: {
    loginTypeText() {
      const typeMap = {
        'wechat': '微信用户',
        'phone': '手机用户',
        'guest': '游客体验'
      }
      return typeMap[this.userInfo.loginType] || ''
    }
  },
  
  onLoad() {
    this.checkLoginStatus()
  },
  
  onShow() {
    this.checkLoginStatus()
    if (this.isLogin) {
      this.getFavorites()
    }
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      this.isLogin = userManager.checkLogin()
      if (this.isLogin) {
        this.userInfo = userManager.getUserInfo()
      } else {
        this.userInfo = {
          nickname: '游客',
          avatar: '/static/logo.png',
          loginType: 'guest'
        }
      }
      
      // 如果是登录状态，获取真实的收藏数据
      if (this.isLogin) {
        this.getFavorites()
      } else {
        this.favoriteCount = 0
        this.playCount = 0
        this.listenTime = '0小时'
      }
    },
    
    // 跳转到收藏
    goToFavorites() {
      if (!this.isLogin) {
        this.goToLogin()
        return
      }
      
      uni.navigateTo({
        url: '/pages/favorites/favorites'
      })
    },
    
    // 显示收藏列表弹窗
    showFavoritesPopup() {
      const favoriteNames = this.favoriteList.map(song => song.name).join('、')
      uni.showModal({
        title: '我的收藏',
        content: `收藏了 ${this.favoriteCount} 首歌曲：
${favoriteNames}`,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    // 跳转到播放历史
    goToHistory() {
      if (!this.isLogin) {
        this.goToLogin()
        return
      }
      
      uni.navigateTo({
        url: '/pages/history/history'
      })
    },
    
    // 跳转到下载管理
    goToDownload() {
      if (!this.isLogin) {
        this.goToLogin()
        return
      }
      uni.showToast({
        title: '下载管理',
        icon: 'none'
      })
    },
    
    // 跳转到设置
    goToSettings() {
      uni.showToast({
        title: '设置',
        icon: 'none'
      })
    },
    
    // 跳转到登录
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    },
    
    // 处理头像点击
    handleAvatarClick() {
      if (!this.isLogin) {
        // 游客状态下点击头像，弹出登录界面
        uni.navigateTo({
          url: '/pages/login/login'
        })
      } else {
        // 已登录状态下点击头像，显示编辑选项
        this.showEditOptions()
      }
    },
    
    // 显示编辑选项
    showEditOptions() {
      if (!this.isLogin) {
        this.goToLogin()
        return
      }
      
      uni.showActionSheet({
        itemList: ['修改头像', '修改昵称'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.changeAvatar()
          } else if (res.tapIndex === 1) {
            this.changeNickname()
          }
        }
      })
    },
    
    // 修改头像
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 显示确认弹窗
          uni.showModal({
            title: '确认修改',
            content: '确定要修改头像吗？',
            success: async (modalRes) => {
              if (modalRes.confirm) {
                try {
                  // 更新用户信息
                  await userManager.updateUserInfo({
                    avatar: tempFilePath
                  })
                  
                  // 更新本地数据
                  this.userInfo = userManager.getUserInfo()
                  
                  uni.showToast({
                    title: '头像修改成功',
                    icon: 'success'
                  })
                } catch (error) {
                  console.error('修改头像失败:', error)
                  uni.showToast({
                    title: '修改失败',
                    icon: 'none'
                  })
                }
              }
            }
          })
        },
        fail: (error) => {
          console.error('选择头像失败:', error)
          uni.showToast({
            title: '选择头像失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 修改昵称
    changeNickname() {
      uni.showModal({
        title: '修改昵称',
        content: '',
        editable: true,
        placeholderText: '请输入新昵称（最多20个字符）',
        success: async (res) => {
          if (res.confirm) {
            const newNickname = res.content.trim()
            
            if (!newNickname) {
              uni.showToast({
                title: '昵称不能为空',
                icon: 'none'
              })
              return
            }
            
            if (newNickname.length > 20) {
              uni.showToast({
                title: '昵称不能超过20个字符',
                icon: 'none'
              })
              return
            }
            
            try {
              // 更新用户信息
              await userManager.updateUserInfo({
                nickname: newNickname
              })
              
              // 更新本地数据
              this.userInfo = userManager.getUserInfo()
              
              uni.showToast({
                title: '昵称修改成功',
                icon: 'success'
              })
            } catch (error) {
              console.error('修改昵称失败:', error)
              uni.showToast({
                title: '修改失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 获取收藏列表（虚拟）
    async getFavorites() {
      if (!this.isLogin) {
        this.favoriteList = []
        this.favoriteCount = 0
        return
      }
      
      try {
        const userId = userManager.getUserId()
        this.favoriteList = mockFavoritesManager.getUserFavorites(userId)
        this.favoriteCount = this.favoriteList.length
      } catch (error) {
        console.error('获取收藏列表失败:', error)
        this.favoriteList = []
        this.favoriteCount = 0
      }
    },
    
    // 处理退出登录
    async handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await userManager.logout()
              this.isLogin = false
              this.userInfo = {
                nickname: '游客',
                avatar: '/static/logo.png',
                loginType: 'guest'
              }
              this.favoriteList = []
              this.favoriteCount = 0
              uni.showToast({
                title: '已退出登录',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '退出失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转到设置
    goToSettings() {
      uni.showToast({
        title: '设置功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style scoped>
.user-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
  padding-top: 120rpx;
}

/* 导航栏样式 */
.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  z-index: 999;
  padding-top: calc(env(safe-area-inset-top, 40rpx) + 40rpx);
  box-shadow: 0 4rpx 20rpx rgba(74, 107, 74, 0.3);
}

.nav-left, .nav-right {
  width: 80rpx;
  display: flex;
  align-items: center;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  color: #ffffff;
  font-weight: 500;
}

.back-text, .settings-text {
  font-size: 36rpx;
  color: #ffffff;
}

.user-header {
  position: relative;
  height: 320rpx;
}

.user-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
}

.bg-image {
  width: 100%;
  height: 100%;
}

.bg-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: rgba(74, 107, 74, 0.3);
}

.user-info {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  height: 100%;
  padding-top: 45rpx;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.8);
  margin-right: 32rpx;
}

.user-details {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.user-name {
  font-size: 36rpx;
  font-weight: 500;
  color: #ffffff;
  line-height: 1.2;
}

.user-desc {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 8rpx;
}

.menu-section {
  background: rgba(255, 255, 255, 0.9);
  margin: 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
  backdrop-filter: blur(10px);
  box-shadow: 0 4rpx 20rpx rgba(74, 107, 74, 0.1);
}

.menu-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #4a6b4a;
  margin-bottom: 24rpx;
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx;
  background: rgba(107, 142, 107, 0.1);
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.menu-item:active {
  background: rgba(107, 142, 107, 0.2);
  transform: scale(0.98);
}

.menu-icon {
  font-size: 48rpx;
  margin-bottom: 16rpx;
}

.menu-text {
  font-size: 24rpx;
  color: #6b8e6b;
}

.stats-section {
  background: rgba(255, 255, 255, 0.9);
  margin: 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
  backdrop-filter: blur(10px);
  box-shadow: 0 4rpx 20rpx rgba(74, 107, 74, 0.1);
}

.stats-grid {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 36rpx;
  font-weight: 600;
  color: #4a6b4a;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #6b8e6b;
}

.action-section {
  padding: 32rpx;
}

.action-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  border: none;
  font-size: 32rpx;
  font-weight: 500;
}

.logout-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(255, 107, 107, 0.3);
}

.login-btn {
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  color: #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(74, 107, 74, 0.3);
}

.btn-text {
  font-size: 32rpx;
}



/* 名称编辑容器 */
.name-edit-container {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.edit-icon {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  padding: 8rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}
</style>